//
//  WCNMeSetTimes(replace)VC.m
//  WCN
//
//  Created by wsj2015 on 15/9/18.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNMeSetTimes(replace)VC.h"
#import "WCNChooseView.h"
#import "WeekDayModel.h"
#import "WCNSetTimeCCell.h"
#import "WCNSetTimeHeaderCRV.h"
#import "Macros.h"
#import "WCButton.h"
#import "UINavigationItem+Offset.h"
#import "WCDefaultManager.h"
#import "NSString+Utilities.h"
#import "WCPopupLayerManager.h"
#import "WCNSettimePartView.h"
#import "Masonry.h"
#import "WCNetworkAccessManager.h"
#import "WCNTemperiodIdForAdd.h"
#import "WCInfoEditView.h"
#import "WCNTempetateSelectTimeModel.h"
#import "WSJAnimationTool.h"
#import "WCNTemperiodIdForAdd.h"

static NSString *cellId = @"WCNSetTimeCCell";
static NSString *headerId = @"WCNSetTimeHeaderCRV";
static NSString *footerId = @"UICollectionReusableView";

#define cellId @"WCNSetTimeCCell"
#define kChooseHeight 30
#define kcollectionFrame CGRectMake(0, kChooseHeight +44, kScreenWidth, kScreenHeight -64 -kChooseHeight -44)
@interface WCNMeSetTimes_replace_VC ()<UICollectionViewDelegate,UICollectionViewDataSource,UIAlertViewDelegate>
{
        UICollectionView *_collectionView;
    
        NSMutableArray *_selectItemArray;

        NSInteger _currentIndex;
    
   
      NSMutableArray *_weekDayArray;
      NSInteger _hosptialTimeFlag;
      NSString *_tempetateName;
    //装第二次请求的 已经选中的数据
      NSMutableArray *_selectDataArray;
    
    
}
@end

@implementation WCNMeSetTimes_replace_VC



- (instancetype)init{
    if (self =[super init]) {
      
        _currentIndex = 0;
        _hosptialTimeFlag = 1;
        _weekDayArray =[NSMutableArray array];
        _selectDataArray =[NSMutableArray array];
    }
    return self;


}
- (void)pageBack
{
    UIAlertView *alerView =[[UIAlertView alloc] initWithTitle:@"提示" message:@"是否放弃模板编辑" delegate:self cancelButtonTitle:@"放弃" otherButtonTitles:@"继续编辑", nil];
    [alerView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex ==0) {
        [self.navigationController popViewControllerAnimated:YES];
    }

}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor =kAppBg;
   
    
    [self conifgNav];
    [self createCollectionView];
//    [self prePareForData:self.dataArray];
    _currentIndex =0;
   
    [self configUI];
    [self prepareData];
    
    
    
    
    
}
- (void)configUI
{
    
    WCNSettimePartView *partView =[WCNSettimePartView viewFromeXib];
    partView.changeBlock = ^(NSInteger isHospitalIn){
        _hosptialTimeFlag =isHospitalIn;
    
    };
    partView.frame =CGRectMake(0, 0, kScreenWidth, 44);
    [self.view addSubview:partView];
    
    [partView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.top.equalTo(self.view.mas_top);
        make.right.equalTo(self.view.mas_right);
        make.height.mas_equalTo(44);
    }];
    
   
    WCNChooseView *chooseView =[[WCNChooseView alloc]initWithFrame:CGRectMake(0, 44, self.view.bounds.size.width, kChooseHeight)];
    chooseView.chooseBlock = ^(NSInteger selectIndex){
        
        _collectionView.alpha =0;
        [UIView animateWithDuration:0.5f animations:^{
            
            _collectionView.alpha =1;
            
        }];
        
        _currentIndex =selectIndex;
        [_collectionView reloadData];
    };
    chooseView.backgroundColor =kAppBg;
    [self.view addSubview:chooseView];
    


}
- (void)prepareData{
    
    
    NSMutableDictionary *params =[NSMutableDictionary  dictionary];
    params[@"unit"] = @(6);
     __weak typeof(self) weakSelf = self;
    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:[UIApplication sharedApplication].keyWindow];
    [[WCNetworkAccessManager sharedMg] POST:kServiceTimePeriodList parameters:params success:^(NSDictionary *responseObject) {
       
        [weakSelf handleWithData:responseObject[@"data"]];
        [_collectionView reloadData];
        
      
        if (self.isEdit == YES) {
             [weakSelf getSelectItemTimeData];
        }
       
    } failure:nil  netError:nil always:^{
        [hud hide:YES];
        
    }];
    
   
 
}

- (void)getSelectItemTimeData
{
    
    NSMutableDictionary *params =[NSMutableDictionary  dictionary];
    params[@"templateId"] = @(self.tempelateId);
    __weak typeof(self) weakSelf = self;
    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:[UIApplication sharedApplication].keyWindow];
    [[WCNetworkAccessManager sharedMg] POST:kTempelateDetail_part parameters:params success:^(NSDictionary *responseObject) {
        
        
        NSDictionary *data =responseObject[@"data"];
        NSDictionary *serviceDict=data[@"serviceTimeTemplate"];
        _tempetateName =serviceDict[@"templateName"];
        [weakSelf rehandTimeDataUsingSelectingTimeData:data[@"detailList"]];
        
        [_collectionView reloadData];
        
    } failure:nil  netError:nil always:^{
        [hud hide:YES];
        
    }];
}

- (void)rehandTimeDataUsingSelectingTimeData:(NSArray *)dataArray
{
    for (NSDictionary *dict in dataArray) {
        WCNTempetateSelectTimeModel *model =[[WCNTempetateSelectTimeModel alloc] init];
        [model setValuesForKeysWithDictionary:dict];
        [_selectDataArray addObject:model];
    }
    // 根据 星期id 和 timeperiod
    for (WCNTempetateSelectTimeModel *selectModel in _selectDataArray) {
        for (int i =1; i<8; i++) {
            WeekDayModel *day =_weekDayArray[i-1];
            for (WCNTemperiodIdForAdd *model in day.amArray) {
                if ([selectModel.weekDayId integerValue] ==i && [model.wcnId integerValue] ==[selectModel.timePeriodId integerValue]) {
                    model.isSelectItem = YES;
                    model.timeType =[selectModel.hosptialTimeFlag integerValue];
                }
            }
            for (WCNTemperiodIdForAdd *model in day.pmArray) {
                if ([selectModel.weekDayId integerValue] ==i && [model.wcnId integerValue] ==[selectModel.timePeriodId integerValue]) {
                    model.isSelectItem = YES;
                    model.timeType =[selectModel.hosptialTimeFlag integerValue];
                }
            }
        }
    }
    

}


- (void)handleWithData:(NSDictionary *)data
{
    NSMutableArray *amArray =[NSMutableArray array];
     NSMutableArray *pmArray =[NSMutableArray array];
    for (NSDictionary *dict in data) {
        WCNTemperiodIdForAdd *model =[[WCNTemperiodIdForAdd alloc] init];
        [model setValuesForKeysWithDictionary:dict[@"currentServiceTime"]];
        if ([model.amPmFlag isEqualToString:@"AM"]) {
            [amArray addObject:model];
        }else{
            [pmArray addObject:model];
        }
    }
    
    
    
    for (int i = 1; i<8; i++) {
        
        //给每个时间加上星期的id
        for (WCNTemperiodIdForAdd *timePeriod in amArray) {
            timePeriod.weekDayId = i;
        }
        for (WCNTemperiodIdForAdd *timePeriod in pmArray) {
            timePeriod.weekDayId = i;
        }
        
        
        WeekDayModel *weekDayModel =[[WeekDayModel alloc] init];
        weekDayModel.wcId =[NSString stringWithFormat:@"%i",i];
        NSMutableArray *dayAmArray= [NSMutableArray array];
        NSMutableArray  *dayPmArray= [NSMutableArray array];
        
        
        for (WCNTemperiodIdForAdd *timePeriod in amArray ) {
            [dayAmArray addObject:[timePeriod copy]];
            
        }
        
         weekDayModel.amArray =dayAmArray;
        for (WCNTemperiodIdForAdd *timePeriod in pmArray ) {
            [dayPmArray addObject:[timePeriod copy]];
           
        }
         weekDayModel.pmArray =dayPmArray;
        
        
        [_weekDayArray addObject:weekDayModel];
        
        
       
    }

}
- (void)conifgNav
{
    self.title =@"服务时间段设置";
    WCButton *rightBtn = [WCButton wcButtonWithType:WCButtonTypeSave];
    [rightBtn addTarget:self action:@selector(saveTempetate:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem addRightBarButtonItem:rightBtn];
}
- (void)saveTempetate:(id)sender
{
 
        //上午和下午的 数据源数组
        
        NSMutableArray *array =[NSMutableArray array];
        for (WeekDayModel *weekDayModel in _weekDayArray) {
            for (WCNTemperiodIdForAdd *timeModel in weekDayModel.amArray) {
                if (timeModel.isSelectItem == YES) {
                    
                    [array addObject:[timeModel modelToDictionary]];
                }
            }
            for (WCNTemperiodIdForAdd *timeModel in weekDayModel.pmArray) {
                if (timeModel.isSelectItem == YES) {
                    [array addObject:[timeModel modelToDictionary]];
                }
            }
            
        }
    if (array.count == 0) {
        [[WCPopupLayerManager shareMg]showTextOnly:@"您未做任何设置或修改~" withView:self.view];
        return;
    }
    
    
    if (self.isEdit == YES) {
        
        [self updateTempetateJson:array];
        return;
    }
    __weak typeof(self) weakSelf =self;
    WCInfoEditView *editView =[[WCInfoEditView alloc] init];
    editView.limitLenth = 10;
    editView.titleLabel.text = @"时间模板名";
    editView.save =^BOOL(NSString *txt){
        _tempetateName = txt;
        [weakSelf updateTempetateJson:array];
        
        return YES;
       
    };
    [editView showIn:self.view animated:YES];
   

    
}

- (void)updateTempetateJson:(NSArray *)array
{
   
//    nurseId 护士ID 必填
//    interval 间隔(5的倍数) 必填
//    templateName 模板名称  必填
//    sttds 详细时间信息 必填
//    templateId 模板ID 修改模板信息时需要
    MBProgressHUD *hud =[[WCPopupLayerManager shareMg] showSimple:self.view];
     NSString *dataStr =[NSString dataToJsonString:array];
        __weak typeof(self) weakSelf =self;
        NSMutableDictionary *params =[NSMutableDictionary dictionary];
        params[@"nurseId"] = @([[WCDefaultManager shareMg] nurseId]);
        params[@"timescale"] =@(6);
        params[@"templateName"] =_tempetateName;
        params[@"sttds"] =dataStr;
    if (self.isEdit == YES) {
        params[@"templateId"] =@(self.tempelateId);
    }
    
    
        [[WCNetworkAccessManager sharedMg]POST:kSaveTemplateUrl_part parameters:params success:^(NSDictionary *responseObject) {
            [[WCPopupLayerManager shareMg] showTextOnly:responseObject[@"data"] withView:[UIApplication sharedApplication].keyWindow];
            if (weakSelf.callBack) {
                weakSelf.callBack();
            }
            [weakSelf.navigationController popViewControllerAnimated:YES];
        } failure:^(NSString *msg) {
    
    
    
        } netError:nil always:^{
            [hud hide:YES];
        }];
    
    



}



// 创建 总模型
//- (void)prePareForData:(NSArray *)dataArray
//{
//  
//    for (int i = 0; i< 7; i++) {
//        WeekDayModel *weekDayModel =[[WeekDayModel alloc]init];
//        weekDayModel.wcId =[NSString stringWithFormat:@"%d",i+1];
//        NSMutableArray *array =[NSMutableArray array];
//        for (timePeroidModel *timePeroidModel in dataArray) {
//            
//            if ([timePeroidModel.weekDayId intValue] == i+1) {
//                [array addObject:timePeroidModel];
//            }
//        }
////        weekDayModel.timePeroidArray =array;
//        
//        //上下午分类
//        NSMutableArray *amArray =[NSMutableArray array];
//        NSMutableArray *pmArray =[NSMutableArray array];
//        for (timePeroidModel *model in array) {
//            if ([model.ampmFlag isEqualToString:@"AM"]) {
//                [amArray addObject:model];
//            }else{
//                [pmArray addObject:model];
//            }
//        }
//        weekDayModel.amArray =amArray;
//        weekDayModel.pmArray =pmArray;
//       
//        
//        [_weekDayArrray addObject:weekDayModel];
//    }
//    //
//    
//}
- (void)createCollectionView
{
    CGRect frame =kcollectionFrame;
    
    //init UICollectionViewFlowLayout
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.itemSize = CGSizeMake((frame.size.width-2.0f)/3.0f, 50);
    flowLayout.headerReferenceSize = CGSizeMake(frame.size.width, 33);
    flowLayout.footerReferenceSize = CGSizeMake(frame.size.width, 20);
    
    //init UICollectionView
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:flowLayout];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.backgroundColor = [UIColor whiteColor];
    
    [collectionView registerNib:[UINib nibWithNibName:cellId bundle:nil] forCellWithReuseIdentifier:@"setTimeCellId"];
    [collectionView registerNib:[UINib nibWithNibName:headerId bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerId];
    [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerId];
    
   
    collectionView.allowsMultipleSelection = YES;
   
    
    
    _collectionView = collectionView;
    [self.view addSubview:collectionView];
    
    
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    
    return 2;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_weekDayArray.count ==0) {
        return 0;
    }
    WeekDayModel *weekDayModel =_weekDayArray[_currentIndex];
    if  (section == 0) {
        return weekDayModel.amArray.count;
    }else{
        return weekDayModel.pmArray.count ;
    }
    
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        WCNSetTimeHeaderCRV *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerId forIndexPath:indexPath];
        if (indexPath.section == 0) {
            header.timeLabel.text = @"上午";
        } else {
            header.timeLabel.text = @"下午";
        }
        
        return header;
    } else if (kind == UICollectionElementKindSectionFooter) {
        UICollectionReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:footerId forIndexPath:indexPath];
        footer.backgroundColor = kBorderColor;
        return footer;
    }
    return nil;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    WeekDayModel *dayModel =_weekDayArray[_currentIndex];
//    timePeroidModel *timeModel;
    WCNTemperiodIdForAdd *model;
    if (indexPath.section == 0) {
        
        model =dayModel.amArray[indexPath.row];
    }else{
        model =dayModel.pmArray[indexPath.row];
    }
    WCNSetTimeCCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"setTimeCellId" forIndexPath:indexPath];
//
    [cell configWithAddModel:model];
    if (model.isSelectItem) {
        [collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
    }else{
        [collectionView deselectItemAtIndexPath:indexPath animated:NO];
    }

    return cell;
    
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//    WeekDayModel *dayModel =_weekDayArrray[_currentIndex];
//    timePeroidModel *timeModel;
//    if (indexPath.section == 0) {
//         timeModel =dayModel.amArray[indexPath.row];
//    }else{
//          timeModel =dayModel.pmArray[indexPath.row];
//    }
    WeekDayModel *dayModel =_weekDayArray[_currentIndex];
    //    timePeroidModel *timeModel;
    WCNTemperiodIdForAdd *model;

   
    NSIndexPath *path;
    if (indexPath.section == 0) {
        
        model =dayModel.amArray[indexPath.row];
        path =[NSIndexPath indexPathForRow:indexPath.row inSection:0];
    }else{
        model =dayModel.pmArray[indexPath.row];
         path =[NSIndexPath indexPathForRow:indexPath.row inSection:1];
    }

    
    model.isSelectItem = YES;
    model.timeType =_hosptialTimeFlag;
    
    [_collectionView reloadItemsAtIndexPaths:@[path]];
//      [_collectionView reloadData];
}

-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
//

    WeekDayModel *dayModel =_weekDayArray[_currentIndex];

    WCNTemperiodIdForAdd *model;
    
    
    NSIndexPath *path;
    if (indexPath.section == 0) {
        
        model =dayModel.amArray[indexPath.row];
        path =[NSIndexPath indexPathForRow:indexPath.row inSection:0];
    }else{
        model =dayModel.pmArray[indexPath.row];
        path =[NSIndexPath indexPathForRow:indexPath.row inSection:1];
    }

    
    model.isSelectItem = NO;
    model.timeType = -1;
  
    [_collectionView reloadItemsAtIndexPaths:@[path]];
}
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    [WSJAnimationTool animationCubeFromTop:cell];


}
@end
